<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Rust WebAssembly 演示</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: #333;
            min-height: 100vh;
        }
        
        .container {
            background: white;
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
        }
        
        h1 {
            text-align: center;
            color: #2c3e50;
            margin-bottom: 30px;
            font-size: 2.5em;
        }
        
        .demo-section {
            margin: 30px 0;
            padding: 20px;
            border: 2px solid #e0e0e0;
            border-radius: 10px;
            background: #f8f9fa;
        }
        
        .demo-section h2 {
            color: #34495e;
            margin-top: 0;
            border-bottom: 2px solid #3498db;
            padding-bottom: 10px;
        }
        
        input, button {
            padding: 10px 15px;
            margin: 5px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
        }
        
        button {
            background: #3498db;
            color: white;
            border: none;
            cursor: pointer;
            transition: background 0.3s;
        }
        
        button:hover {
            background: #2980b9;
        }
        
        .result {
            background: #ecf0f1;
            padding: 15px;
            border-radius: 5px;
            margin-top: 10px;
            font-family: 'Courier New', monospace;
            white-space: pre-wrap;
            border-left: 4px solid #3498db;
        }
        
        .loading {
            color: #7f8c8d;
            font-style: italic;
        }
        
        .error {
            color: #e74c3c;
            background: #fdf2f2;
            border-left-color: #e74c3c;
        }
        
        .success {
            color: #27ae60;
            background: #f0f9f0;
            border-left-color: #27ae60;
        }
        
        .grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
        }
        
        .feature-card {
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            border-left: 4px solid #3498db;
        }
        
        .feature-card h3 {
            margin-top: 0;
            color: #2c3e50;
        }
        
        .status {
            text-align: center;
            padding: 20px;
            font-size: 1.2em;
            font-weight: bold;
        }
        
        .status.loading {
            color: #f39c12;
        }
        
        .status.success {
            color: #27ae60;
        }
        
        .status.error {
            color: #e74c3c;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🚀 Rust WebAssembly 演示</h1>
        
        <div id="status" class="status loading">正在加载 WebAssembly 模块...</div>
        
        <div id="demo-content" style="display: none;">
            <div class="demo-section">
                <h2>🧮 计算器演示</h2>
                <p>展示 Rust 在 WebAssembly 中的基本数学计算能力</p>
                <input type="number" id="calc-a" placeholder="数字 A" value="10">
                <input type="number" id="calc-b" placeholder="数字 B" value="5">
                <button onclick="calcDemo()">计算</button>
                <div id="calc-result" class="result"></div>
            </div>
            
            <div class="demo-section">
                <h2>⚡ 性能测试</h2>
                <p>比较 Rust WebAssembly 与 JavaScript 的计算性能</p>
                <input type="number" id="perf-iterations" placeholder="迭代次数" value="1000000">
                <button onclick="perfTest()">运行 Rust 测试</button>
                <button onclick="jsPerfTest()">运行 JavaScript 测试</button>
                <div id="perf-result" class="result"></div>
            </div>
            
            <div class="demo-section">
                <h2>🔢 数学函数</h2>
                <p>展示 Rust 的高性能数学计算</p>
                <input type="number" id="fib-n" placeholder="斐波那契数列项数" value="20">
                <button onclick="fibDemo()">计算斐波那契</button>
                <br><br>
                <input type="number" id="prime-n" placeholder="质数检查" value="17">
                <button onclick="primeDemo()">检查质数</button>
                <div id="math-result" class="result"></div>
            </div>
            
            <div class="demo-section">
                <h2>🎨 图像处理</h2>
                <p>展示 Rust 在图像处理中的性能优势</p>
                <canvas id="canvas" width="400" height="300" style="border: 1px solid #ddd; display: block; margin: 10px 0;"></canvas>
                <br>
                <button onclick="generatePattern()">生成图案</button>
                <button onclick="applyGrayscale()">灰度化</button>
                <button onclick="applyBlur()">模糊处理</button>
                <div id="image-result" class="result"></div>
            </div>
            
            <div class="demo-section">
                <h2>🎮 游戏引擎</h2>
                <p>展示 Rust 在实时计算中的性能</p>
                <canvas id="game-canvas" width="600" height="400" style="border: 1px solid #ddd; display: block; margin: 10px 0;"></canvas>
                <br>
                <button onclick="addEntity()">添加实体</button>
                <button onclick="startGame()">开始游戏</button>
                <button onclick="stopGame()">停止游戏</button>
                <div id="game-result" class="result"></div>
            </div>
            
            <div class="grid">
                <div class="feature-card">
                    <h3>🚀 高性能</h3>
                    <p>Rust 编译为 WebAssembly 后，性能接近原生代码，比 JavaScript 快数倍。</p>
                </div>
                <div class="feature-card">
                    <h3>🛡️ 内存安全</h3>
                    <p>编译时保证内存安全，避免缓冲区溢出等常见安全问题。</p>
                </div>
                <div class="feature-card">
                    <h3>🔄 零成本抽象</h3>
                    <p>高级抽象在编译时被优化掉，运行时性能与手写代码相当。</p>
                </div>
                <div class="feature-card">
                    <h3>🌐 跨平台</h3>
                    <p>一次编写，到处运行。支持所有现代浏览器和 Node.js 环境。</p>
                </div>
            </div>
        </div>
    </div>

    <script type="module">
        let wasmModule;
        let calculator;
        let imageProcessor;
        let gameEngine;
        let gameRunning = false;
        let gameAnimationId;
        
        // 加载 WebAssembly 模块
        async function loadWasm() {
            try {
                const status = document.getElementById('status');
                status.textContent = '正在加载 WebAssembly 模块...';
                status.className = 'status loading';
                
                // 这里需要先编译 WebAssembly 模块
                // 实际使用时需要先运行: wasm-pack build --target web
                const wasmUrl = './pkg/wasm_demo.js';
                const wasm = await import(wasmUrl);
                await wasm.default();
                
                wasmModule = wasm;
                calculator = new wasm.Calculator();
                imageProcessor = new wasm.ImageProcessor(400, 300);
                gameEngine = new wasm.GameEngine(600, 400);
                
                status.textContent = 'WebAssembly 模块加载成功！';
                status.className = 'status success';
                document.getElementById('demo-content').style.display = 'block';
                
                // 初始化演示
                generatePattern();
                addEntity();
                
            } catch (error) {
                console.error('加载 WebAssembly 失败:', error);
                const status = document.getElementById('status');
                status.textContent = 'WebAssembly 模块加载失败。请确保已编译模块。';
                status.className = 'status error';
                
                // 显示编译说明
                const demoContent = document.getElementById('demo-content');
                demoContent.innerHTML = `
                    <div class="demo-section">
                        <h2>📋 编译说明</h2>
                        <p>要运行此演示，请先编译 WebAssembly 模块：</p>
                        <div class="result">
# 安装 wasm-pack
cargo install wasm-pack

# 编译 WebAssembly 模块
cd wasm-demo
wasm-pack build --target web

# 启动本地服务器
python -m http.server 8000
                        </div>
                        <p>然后在浏览器中访问 <code>http://localhost:8000</code></p>
                    </div>
                `;
                demoContent.style.display = 'block';
            }
        }
        
        // 计算器演示
        window.calcDemo = function() {
            if (!wasmModule) return;
            
            const a = parseFloat(document.getElementById('calc-a').value) || 0;
            const b = parseFloat(document.getElementById('calc-b').value) || 0;
            
            const result1 = calculator.add(a, b);
            const result2 = calculator.multiply(a, b);
            const result3 = calculator.add(result1, result2);
            
            const result = `计算结果：
${a} + ${b} = ${result1}
${a} × ${b} = ${result2}
${result1} + ${result2} = ${result3}

计算历史：
${calculator.get_history()}`;
            
            document.getElementById('calc-result').textContent = result;
        };
        
        // 性能测试
        window.perfTest = function() {
            if (!wasmModule) return;
            
            const iterations = parseInt(document.getElementById('perf-iterations').value) || 1000000;
            const result = wasmModule.performance_test(iterations);
            document.getElementById('perf-result').textContent = result;
        };
        
        window.jsPerfTest = function() {
            const iterations = parseInt(document.getElementById('perf-iterations').value) || 1000000;
            const start = performance.now();
            
            let sum = 0.0;
            for (let i = 0; i < iterations; i++) {
                sum += Math.sqrt(i).sin().cos();
            }
            
            const end = performance.now();
            const duration = end - start;
            
            const result = `JavaScript 执行 ${iterations} 次迭代耗时: ${duration.toFixed(2)}ms, 结果: ${sum.toFixed(6)}`;
            document.getElementById('perf-result').textContent = result;
        };
        
        // 数学函数演示
        window.fibDemo = function() {
            if (!wasmModule) return;
            
            const n = parseInt(document.getElementById('fib-n').value) || 20;
            const result = wasmModule.fib_demo(n);
            document.getElementById('math-result').textContent = result;
        };
        
        window.primeDemo = function() {
            if (!wasmModule) return;
            
            const n = parseInt(document.getElementById('prime-n').value) || 17;
            const result = wasmModule.prime_demo(n);
            document.getElementById('math-result').textContent = result;
        };
        
        // 图像处理演示
        window.generatePattern = function() {
            if (!imageProcessor) return;
            
            const canvas = document.getElementById('canvas');
            const ctx = canvas.getContext('2d');
            
            // 生成彩色图案
            for (let y = 0; y < 300; y++) {
                for (let x = 0; x < 400; x++) {
                    const r = Math.floor(255 * (x / 400));
                    const g = Math.floor(255 * (y / 300));
                    const b = Math.floor(255 * ((x + y) / 700));
                    imageProcessor.set_pixel(x, y, r, g, b, 255);
                }
            }
            
            updateCanvas();
            document.getElementById('image-result').textContent = '图案生成完成！';
        };
        
        window.applyGrayscale = function() {
            if (!imageProcessor) return;
            
            imageProcessor.apply_grayscale();
            updateCanvas();
            document.getElementById('image-result').textContent = '灰度化处理完成！';
        };
        
        window.applyBlur = function() {
            if (!imageProcessor) return;
            
            imageProcessor.apply_blur(2);
            updateCanvas();
            document.getElementById('image-result').textContent = '模糊处理完成！';
        };
        
        function updateCanvas() {
            const canvas = document.getElementById('canvas');
            const ctx = canvas.getContext('2d');
            const imageData = ctx.createImageData(400, 300);
            const data = imageProcessor.get_data();
            
            for (let i = 0; i < data.length; i++) {
                imageData.data[i] = data[i];
            }
            
            ctx.putImageData(imageData, 0, 0);
        }
        
        // 游戏引擎演示
        window.addEntity = function() {
            if (!gameEngine) return;
            
            const colors = ['#ff6b6b', '#4ecdc4', '#45b7d1', '#96ceb4', '#feca57'];
            const color = colors[Math.floor(Math.random() * colors.length)];
            const x = Math.random() * 600;
            const y = Math.random() * 400;
            const radius = 10 + Math.random() * 20;
            
            const id = gameEngine.add_entity(x, y, radius, color);
            gameEngine.set_velocity(id, (Math.random() - 0.5) * 200, (Math.random() - 0.5) * 200);
            
            updateGameCanvas();
        };
        
        window.startGame = function() {
            if (gameRunning) return;
            
            gameRunning = true;
            gameLoop();
            document.getElementById('game-result').textContent = '游戏已开始！';
        };
        
        window.stopGame = function() {
            gameRunning = false;
            if (gameAnimationId) {
                cancelAnimationFrame(gameAnimationId);
            }
            document.getElementById('game-result').textContent = '游戏已停止。';
        };
        
        function gameLoop() {
            if (!gameRunning) return;
            
            gameEngine.update(1/60); // 60 FPS
            updateGameCanvas();
            
            gameAnimationId = requestAnimationFrame(gameLoop);
        }
        
        function updateGameCanvas() {
            const canvas = document.getElementById('game-canvas');
            const ctx = canvas.getContext('2d');
            
            ctx.clearRect(0, 0, 600, 400);
            
            const entities = JSON.parse(gameEngine.get_entities_json());
            entities.forEach(entity => {
                ctx.beginPath();
                ctx.arc(entity.x, entity.y, entity.radius, 0, 2 * Math.PI);
                ctx.fillStyle = entity.color;
                ctx.fill();
                ctx.stroke();
            });
        }
        
        // 页面加载完成后初始化
        loadWasm();
    </script>
</body>
</html>


